import base64
import logging
import requests
from patch_tracking import settings

log = logging.getLogger(__name__)

ORG_URL = "https://gitee.com/api/v5/orgs"
REPO_URL = "https://gitee.com/api/v5/repos"
OWNER = settings.GITEE_OWNER
TOKEN = settings.GITEE_ACCESS_TOKEN


def get_repo():
    '''
    获取指定组织下的所有仓库
    :param org_url:
    :param org:
    :param token:
    :return:
    '''
    url = '/'.join([ORG_URL, OWNER, 'repos'])
    param = {'access_token': TOKEN}
    repo_list = list()

    response = requests.get(url, params=param)
    for item in response.json():
        repo_name = item['full_name'].split('/')[1]
        repo_list.append(repo_name)
    return repo_list


def get_branch(repo):
    '''
    获取指定仓库的所有分支
    :param repo_url:
    :param repos:
    :param token:
    :return:
    '''
    param = {'access_token': TOKEN}
    branch_list = list()
    url = '/'.join([REPO_URL, OWNER, repo, 'branches'])

    response = requests.get(url, params=param)
    for item in response.json():
        branch_list.append(item['name'])
    return branch_list


def get_yaml_content(repo, branch):
    '''
    获取指定仓库，指定分支的yaml文件内容
    :param repo_url:
    :param repo:
    :param branch:
    :param token:
    :return:
    '''
    yaml_content_dict = dict()
    path = repo + '.yaml'
    url = '/'.join([REPO_URL, OWNER, repo, 'contents', path])
    param = {'access_token': TOKEN, 'ref': branch}
    response = requests.get(url, params=param).json()
    content = str(base64.b64decode(response['content']), encoding='utf-8')
    for item in content.split('\n'):
        if item:
            key = item.split(':')[0].strip(' ')
            value = item.split(':')[1].strip(' ')
            yaml_content_dict[key] = value
    return yaml_content_dict


def get_path_content(repo, branch, path):
    '''
    获取指定仓库，指定分支的文件内容
    :param repo_url:
    :param repo:
    :param branch:
    :param token:
    :return:
    '''
    url = '/'.join([REPO_URL, OWNER, repo, 'contents', path])
    param = {'access_token': TOKEN, 'ref': branch}
    ret = requests.get(url, params=param).json()
    # content = str(base64.b64decode(r['content']), encoding='utf-8')
    return ret


def post_create_branch(repo, branch, new_branch):
    '''
    创建分支
    :param repo_url:
    :param owner:
    :param repo:
    :param branch:
    :param new_branch:
    :param token:
    :return:
    '''
    url = '/'.join([REPO_URL, OWNER, repo, 'branches'])
    data = {'access_token': TOKEN, 'refs': branch, 'branch_name': new_branch}
    response = requests.post(url, data=data)
    if response.status_code == 201:
        return 'success'

    return response.json()


def post_upload_patch(repo, branch, last_scm_commit, patch_file_content, cur_time, commit_url):
    '''
    上传两个commit之间的patch文件
    :param repo_url:
    :param owner:
    :param repo:
    :param branch:
    :param patch_file_name:
    :param patch_file_content:
    :return:
    '''
    patch_file_name = last_scm_commit + '.patch'
    url = '/'.join([REPO_URL, OWNER, repo, 'contents', patch_file_name])
    content = base64.b64encode(patch_file_content.encode("utf-8"))
    message = '[patch tracking] ' + cur_time + ' - ' + commit_url + '\n'
    data = {'access_token': TOKEN, 'content': content, 'message': message, 'branch': branch}
    response = requests.post(url, data=data)
    if response.status_code == 201:
        return 'success'

    return response.json()


def put_upload_spec(repo, branch, cur_time, spec_content, spec_sha):
    '''
    上传两个commit之间的patch文件
    :param repo_url:
    :param owner:
    :param repo:
    :param branch:
    :param patch_file_name:
    :param patch_file_content:
    :return:
    '''
    spec_file_name = repo + '.spec'
    url = '/'.join([REPO_URL, OWNER, repo, 'contents', spec_file_name])
    content = base64.b64encode(spec_content.encode("utf-8"))
    message = '[patch tracking] ' + cur_time + ' - ' + 'update spec file' + '\n'
    data = {
        'access_token': TOKEN,
        'owner': OWNER,
        'repo': repo,
        'path': spec_file_name,
        'content': content,
        'message': message,
        'branch': branch,
        'sha': spec_sha
    }
    response = requests.put(url, data=data)
    if response.status_code == 200:
        return 'success'

    return response.json()


def post_create_issue(repo, issue_body, cur_time):
    '''
    创建issue
    :param repo_url:
    :param owner:
    :param repo:
    :param issue_body:
    :return:
    '''
    url = '/'.join([REPO_URL, OWNER, 'issues'])
    data = {'access_token': TOKEN, 'repo': repo, 'title': '[patch tracking] ' + cur_time, 'body': issue_body}
    response = requests.post(url, data=data)
    if response.status_code == 201:
        return 'success', response.json()['number']

    return 'error', response.json()


def post_create_pull_request(repo, branch, patch_branch, issue_num, cur_time):
    '''
    创建PR
    :param repo_url:
    :param owner:
    :param repo:
    :param branch:
    :param patch_branch:
    :param issue_num:
    :return:
    '''
    url = '/'.join([REPO_URL, OWNER, repo, 'pulls'])
    data = {
        'access_token': TOKEN,
        'repo': repo,
        'title': '[patch tracking] ' + cur_time,
        'head': patch_branch,
        'base': branch,
        'body': '#' + issue_num,
        "prune_source_branch": "true"
    }
    response = requests.post(url, data=data)
    if response.status_code == 201:
        return 'success'

    return response.json()
